﻿using MiniExcelLibs;
using MiniExcelLibs.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExportTool
{
    public class ExcelHelp
    {
        private static readonly int Max = 65530;
        public static void ExportToExcel<T>(IEnumerable<T> list, string path)
        {
            int sheetsCount = GetSheetsCount(list.Count());
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            for (int i = 1; i <= sheetsCount; i++)
            {
                dictionary.Add("Sheet" + i, GetPageDate(list, i));
            }

            MiniExcel.SaveAs(path, dictionary, printHeader: true, "Sheet1", ExcelType.UNKNOWN, new OpenXmlConfiguration
            {
                TableStyles = TableStyles.None,
                AutoFilter = false
            });
        }

        private static IEnumerable<T> GetPageDate<T>(IEnumerable<T> list, int i)
        {
            return list.Skip(Max * (i - 1)).Take(Max);
        }

        private static int GetSheetsCount(int rowsCount)
        {
            int num = (int)Math.Ceiling((double)rowsCount / (double)Max);
            return (num < 1) ? 1 : num;
        }
    }
}
